// Copyright (c) 2024, lanlian and contributors
// For license information, please see license.txt

frappe.ui.form.on("EMS Lubrication Plan", {
	refresh(frm) {
        // 润滑方案下推润滑单
        frm.add_custom_button(__('Make EMS Lubrication Doc'), () => {
            frappe.model.open_mapped_doc({
                method: "ems.equipment_managerment_system.doctype.ems_lubrication_plan.ems_lubrication_plan.make_lubrication_doc",
                frm: cur_frm,
                freeze_message: __("Creating Lubrication ...")
            });
        });
        // 从指定的润滑模版复制润滑项目,逐行添加至子表
        frm.fields_dict["items"].grid.add_custom_button(__('Get From Template'), 
			function() {
                frappe.db.get_doc('EMS Lubrication Plan Template', frm.doc.template_select)
                .then(doc => {
                    doc.items.forEach(item => {
                        frm.add_child('items', {
                            figure_number: item.figure_number,
                            item_code: item.item_code,
                            uom: item.uom,
                            qty: item.qty,
                        });
                    });
                    frm.doc.lubrication_plan = doc.template_title;
                    frm.doc.periodicity = doc.periodicity;
                })
                .then( () => { frm.refresh_fields();})
        });
        frm.fields_dict["items"].grid.grid_buttons.find('.btn-custom').removeClass('btn-default').addClass('btn-primary');
	},
});
